import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { routerRedux } from 'dva/router';
import { fakeAccountLogin, getFakeCaptcha,tokenLogin } from './service';
import { getPageQuery, setAuthority } from './utils/utils';
import { setLoginInfo } from '../../../utils/BdHelper';
import { router } from 'umi';
import customerSettings from '../../../../config/customSettings';

export interface StateType {
  code?: number;
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  msg?: string;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    getCaptcha: Effect;
    tokenLogin:Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'userAndlogin',

  state: {
    code: undefined,
    msg: '',
  },

  effects: {
    *login({ payload }, { call, put }) {

      const response = yield call(fakeAccountLogin, payload);

      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code === 0) {
        console.log('crmmmm---->response', response)
        setLoginInfo(response.data);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }

        if(customerSettings.appName === 'crm'){
          let path = response.data.jump_url ?  response.data.jump_url : '/dashboard/crm/report/dashboard/index';
          yield put(routerRedux.replace(path));
        }else if(customerSettings.appName === 'trip'){
          let path = response.data.jump_url ?  response.data.jump_url : '/statistics/userStatisticalx';
          yield put(routerRedux.replace(path));
        }else{
          let path = response.data.jump_url ?  response.data.jump_url : '/systemmanage/manager';
          yield put(routerRedux.replace(path));
        }
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *tokenLogin({ payload }, { call,put }){
      console.log('token登录')
      const response = yield call(tokenLogin, payload);
      console.log('response',response)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // tokenLogin(payload).then(response=>{
      //   console.log(response)
      //   if(response.code === 0){
      //     router.push(`/taskManagement/taskList`)
      //   }  
      // })

      // Login successfully
      if (response.code === 0) {
        console.log('response',response)
        setLoginInfo(response.data);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/taskManagement/taskList'));
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.data.currentAuthority);
      console.log('response-payload-->', payload)
      return {
        ...state,
        code: payload.code,
        type: payload.type || 'account',
        msg: payload.message
      };
    },
  },
};

export default Model;
